package com.xu.sys.servlet;

/**
 * 处理文件上传操作的Servlet
 */

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

@WebServlet(name = "uploadServlet",urlPatterns = {"/sys/uploadServlet"})
public class UploadServlet extends HttpServlet {
    public static final String UPLOAD_DIRECTORY = "d:\\bookFile\\";
    //private static final String UPLOAD_DIRECTORY = "upload";
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 检测是否是文件
        // 这个路径相对当前应用的目录
        String uploadPath = UPLOAD_DIRECTORY;
        // 如果目录不存在则创建
        File uploadDir = new File(UPLOAD_DIRECTORY);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> fileItems = upload.parseRequest(request);
            if(fileItems != null && fileItems.size() > 0){
                for (FileItem fileItem : fileItems) {
                    if(!fileItem.isFormField()){
// 表明该信息上传的文件信息
                        String fileName = new File(fileItem.getName()).getName();
// 上传的文件名称
                        fileName = new Date().getTime() +
                                fileName.substring(fileName.lastIndexOf("."));
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
// 在控制台输出文件的上传路径
                        System.out.println(filePath);
// 保存文件到硬盘
                        fileItem.write(storeFile);
//request.setAttribute("message", "文件上传成功!");
// 把生成的文件名称返回给客户端
                        PrintWriter writer = response.getWriter();
                        writer.write(fileName);
                        writer.flush();
                        writer.close();
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
